﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCompany.MyProject.Model;

/// <summary>
/// 通用分页信息
/// </summary>
/// <typeparam name="T"></typeparam>
public class PageModel<T> 
{
    /// <summary>
    /// 当前页标
    /// </summary>
    public int PageIndex { get; set; } = 1;

    /// <summary>
    /// 每页大小
    /// </summary>
    public int PageSize { get; set; } = 10;

    /// <summary>
    /// 总页数
    /// </summary>
    public int PageCount => (int)Math.Ceiling((double)DataCount / PageSize);

    /// <summary>
    /// 数据总数据
    /// </summary>
    public int DataCount { get; set; } = 0;

    /// <summary>
    /// 返回数据
    /// </summary>
    public List<T> Data { get; set; }

    /// <summary>
    /// 默认构造函数
    /// </summary>
    public PageModel() { }

    /// <summary>
    /// 有参数构造函数
    /// </summary>
    /// <param name="pageIndex"></param>
    /// <param name="dataCount"></param>
    /// <param name="pageSize"></param>
    /// <param name="data"></param>
    public PageModel(int pageIndex,int dataCount,int pageSize,List<T> data)
    {
        PageIndex =pageIndex;
        DataCount =dataCount;
        PageSize =pageSize;
        Data =data;
    }

    /// <summary>
    /// 转换到 PageModel 类型
    /// </summary>
    /// <typeparam name="TOut"></typeparam>
    /// <returns></returns>
    public PageModel<TOut> ConvertTo<TOut>()
    {
        return new PageModel<TOut>(PageIndex, DataCount, PageSize, default);
    }

    /// <summary>
    /// 一般用来转换Model到对应的视图模型
    /// </summary>
    /// <typeparam name="TOut"></typeparam>
    /// <param name="mapper"></param>
    /// <returns></returns>
    public PageModel<TOut> ConvertTo<TOut>(IMapper mapper)
    {
        var model = ConvertTo<TOut>();
        if (Data != null)
        {
            model.Data = mapper.Map<List<TOut>>(Data);
        }
        return model;
    }

    /// <summary>
    /// Model 到 DTO 可用传递转换的选项
    /// </summary>
    /// <typeparam name="TOut"></typeparam>
    /// <param name="mapper"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public PageModel<TOut> ConvertTo<TOut>(IMapper mapper,Action<IMappingOperationOptions> options)
    {
        var model = ConvertTo<TOut>();
        if (Data != null)
        {
            model.Data = mapper.Map<List<TOut>>(Data,options);
        }
        return model;
    }
}
